import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
import 'package:zhuanzu/utils/api.dart';

import '../widgets/RandomGeoAvatarPainter.dart';

class V2exDetailPage extends StatefulWidget {
  final int postId;
  final String title;

  const V2exDetailPage({super.key, required this.postId, required this.title});

  @override
  State<V2exDetailPage> createState() => _V2exDetailPageState();
}

class _V2exDetailPageState extends State<V2exDetailPage> {
  List<dynamic> _comments = [];
  bool _loading = true;
  bool _hasMore = true; // 是否还有更多数据
  bool _isFetching = false; // 当前是否正在请求
  int _page = 1; // 当前页码
  final int _pageSize = 15;

  final ScrollController _scrollController = ScrollController();

  @override
  void initState() {
    super.initState();
    _fetchComments();
    _scrollController.addListener(() {
      if (_scrollController.position.pixels >=
              _scrollController.position.maxScrollExtent - 100 &&
          !_isFetching &&
          _hasMore) {
        _fetchComments();
      }
    });
  }

  @override
  void dispose() {
    _scrollController.dispose();
    super.dispose();
  }

  Future<void> _fetchComments() async {
    if (_isFetching || !_hasMore) return;

    setState(() {
      _isFetching = true;
    });

    try {
      final res = await Api.get(
        '/comments/simpleCom',
        params: {
          'postId': widget.postId.toString(),
          'page': _page.toString(),
          'size': _pageSize.toString(),
        },
      );

      if (res['code'] == 0) {
        final data = res['data'] as Map<String, dynamic>;
        final records = data['records'] as List<dynamic>;

        setState(() {
          _comments.addAll(records);
          _hasMore = records.length == _pageSize;
          if (_hasMore) _page++;
        });
      } else {
        throw Exception('接口返回失败: ${res['msg']}');
      }
    } catch (e) {
      print("加载评论失败: $e");
    } finally {
      setState(() {
        _isFetching = false;
        _loading = false;
      });
    }
  }

  String _formatDate(String? dateStr) {
    if (dateStr == null || dateStr.isEmpty) return '';
    try {
      final dt = DateTime.parse(dateStr);
      return DateFormat('MM-dd HH:mm').format(dt);
    } catch (e) {
      return '';
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text(widget.title)),
      body: _loading
          ? const Center(child: CircularProgressIndicator())
          : _comments.isEmpty
          ? const Center(child: Text("暂无评论", style: TextStyle(fontSize: 16)))
          : ListView.separated(
              controller: _scrollController,
              itemCount: _comments.length + 1, // 多加一个尾部加载状态
              separatorBuilder: (_, __) => const Divider(height: 1),
              itemBuilder: (context, index) {
                if (index == _comments.length) {
                  // 尾部加载状态
                  if (_hasMore) {
                    return const Padding(
                      padding: EdgeInsets.symmetric(vertical: 16),
                      child: Center(child: CircularProgressIndicator()),
                    );
                  } else {
                    return const Padding(
                      padding: EdgeInsets.symmetric(vertical: 16),
                      child: Center(child: Text("没有更多了")),
                    );
                  }
                }
                final comment = _comments[index];

                final avatarUrl = comment['avatar']?.toString();
                final fallbackSeed = (comment['id'] ?? index).toString();
                final diceBearUrl =
                    'https://avatars.dicebear.com/api/avataaars/$fallbackSeed.svg';

                return ListTile(
                  leading: ClipOval(
                    child: RandomGeoAvatar(
                      seed: (comment['id'] ?? index).hashCode,
                      size: 40,
                    ),
                  ),
                  title: Text(comment['content'] ?? '无内容'),
                  subtitle: Text(
                    _formatDate(comment['createdAt']),
                    style: const TextStyle(fontSize: 12, color: Colors.grey),
                  ),
                );
              },
            ),
    );
  }
}
